﻿// 创建ML.NET环境
using SimpleNeuralNetwork.Models;
using System.ComponentModel.DataAnnotations;
using TensorFlow;

internal class Program
{
    private static void Main(string[] args)
    {
        // 定义模型
        var model = new TFModel();

        // 定义层
        var input = model.Input(2); // 输入层有两个神经元
        var hidden = model.FullyConnected(input, 3, TFActivations.Sigmoid); // 隐藏层有三个神经元
        var output = model.FullyConnected(hidden, 1, TFActivations.Sigmoid); // 输出层有一个神经元

        // 定义损失函数和优化器
        var target = model.Placeholder(TFDataType.Float);
        var loss = model.ReduceMean(model.Square(model.Subtract(output, target)));
        var optimizer = new TFOptimizer.Adam(learningRate: 0.1f).Minimize(loss);

        // 创建会话
        using (var session = new TFSession())
        {
            session.StartProfiling();

            // 初始化模型参数
            session.Run(model.GlobalVariablesInitializer());

            // 准备数据
            var inputTensor = new TFTensor(new float[,] { { 0, 0 }, { 0, 1 }, { 1, 0 }, { 1, 1 } });
            var targetTensor = new TFTensor(new float[,] { { 0 }, { 1 }, { 1 }, { 0 } });

            // 训练模型
            for (int i = 0; i < 1000; i++)
            {
                session.Run(optimizer, (input, inputTensor), (target, targetTensor));
            }

            // 测试模型
            var testInput = new TFTensor(new float[,] { { 0, 1 } });
            var testResult = session.Run(output, (input, testInput));
            var prediction = (float)testResult.GetValue();

            Console.WriteLine($"预测结果: {prediction}");

            session.CloseSession();
        }
    }
}